package com.ruoyi.web.timer;

import com.ruoyi.web.common.Const;
import com.ruoyi.web.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * 无人船定时任务
 */
@Slf4j
@Component
@Lazy(false)
public class MqttPublishScheduled {
    private volatile boolean isOpen = true;
    @Autowired
    private DeviceService deviceService;

    @Scheduled(cron = "0/7 * * * * ?")
    public void heartbeatMqtt() {
        if (!isOpen || deviceService == null) {
            return;
        }
        /*String topic = Const.DEVICE_MQTT_JP_TOPIC;
        String data = "10";
        deviceService.publish(topic,data);*/
//        log.info("心跳主题：[{}]，内容: [{}]", topic, data);
        deviceService.checkBoatOffline();
    }

    //    @Scheduled(fixedRate = 200)
    public void netMqtt() {
        if (!isOpen || deviceService == null) {
            return;
        }
        String topic = Const.DEVICE_MQTT_JP_TOPIC;
        Random r = new Random();
        int num1 = r.nextInt(10) + 1;
        int num2 = r.nextInt(10) + 1;
        String data1 = "1,0,1," + num1 + ",3.3," + num2 + ",5.5,6.6,7.7,8.8";
        String data2 = "2,1,2,100,1,2,121.123123,31.123123,121.126123,31.126123";
        String data4 = "4,1,0";
        deviceService.publish(topic, data1);
        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data1);
//        deviceService.publish(topic,data2);
//        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data2);
//        deviceService.publish(topic,data4);
//        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data4);
    }

    //    @Scheduled(fixedRate = 1000)
    public void netMqtt2() {
        if (!isOpen || deviceService == null) {
            return;
        }
        String topic = Const.DEVICE_MQTT_JP_TOPIC;
        Random r = new Random();
        int num1 = r.nextInt(10) + 1;
        String data1 = "1,0,1,2.2,3.3,4.4,5.5,6.6,7.7,8.8";
        String data2 = "2,1,2,100," + num1 + ",2,121.123123,31.123123,121.126123,31.126123";
        String data4 = "4,1,0";
//        deviceService.publish(topic,data1);
//        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data1);
        deviceService.publish(topic, data2);
        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data2);
        deviceService.publish(topic, data4);
        log.info("netMqtt主题：[{}]，内容: [{}]", topic, data4);
    }

    /**
     * 关闭
     */
    public synchronized void close() {
        this.isOpen = false;
    }

    /**
     * 开启
     */
    public synchronized void open() {
        this.isOpen = true;
    }


}
